<template>
  <main-content title="商品管理">
    <template #tab-bar>
      <el-radio-group v-model="searchForm.onlineStatus">
        <el-radio-button
          v-for="(item, index) in filterList"
          :key="index"
          plain
          :label="item.value"
        >
          {{ item.label }}<span>({{ item.count }})</span>
        </el-radio-button>
      </el-radio-group>
    </template>

    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.name"
              clearable
              placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              v-model="searchForm.categoryId"
              placeholder="请选择商品分类"
              clearable
            >
              <el-option
                v-for="item in goodsCateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <goods-supplier-filter
            url="/mall/admin/product/getStore2"
            @change="({ selected }) => (searchForm.storeId = selected)"
          />
          <el-form-item label="积分范围">
            <div
              class="form-content"
              style="display: flex; align-items: center"
            >
              <el-input
                v-model.number="searchForm.prePrice"
                placeholder="请输入积分下限"
              >
                <template #append>
                  分
                </template>
              </el-input>
              <span style="margin: 0 10px">至</span>
              <el-input
                v-model.number="searchForm.aftPrice"
                placeholder="请输入积分上限"
              >
                <template #append>
                  分
                </template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="商品类型">
            <el-select
              v-model="searchForm.goodsType"
              placeholder="请选择商品类型"
              clearable
            >
              <el-option
                v-for="(option, index) in merchantProductTypes"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <!--          <ins-cascader-filter @change="(value) => searchForm.queryInsIds = value"></ins-cascader-filter>-->
          <el-form-item>
            <el-button
              type="primary"
              @click="refreshList"
            >
              查询
            </el-button>
            <el-button
              v-has="['08030101']"
              type="primary"
              @click="showGoodSelect"
            >
              新增商品
            </el-button>
            <!-- TODO 加权限 -->
            <el-button
              type="primary"
              @click="showExportData = true"
            >
              导出
            </el-button>
          </el-form-item>
        </template>
      </search-bar>
    </template>

    <layout-table
      id="goods-list"
      ref="goodsListRef"
      url="/mall/admin/product/pageProduct"
      :param="{...searchForm,goodsIds:goodsIds}"
      :row-key="(row: any) => String(row.id)"
      @row-click="handleRowClick"
    >
      <el-table-column type="expand">
        <template #default="scope">
          <div
            v-expand-table-auto-resize="{parentTableSelector: '#goods-list' }"
            class="expand-table-wrapper"
          >
            <el-table :data="scope.row?.products ?? []">
              <col-product-id />
              <col-product-name />
              <col-product-thumbnail-url />
              <col-product-original-price />
              <col-product-sale-price />
              <col-product-total-stock />
              <col-product-stock />
              <col-product-switch-online-status :before-change="_switchProductStatus" />
              <col-product-update-time />
              <el-table-column
                v-has="['08030106', '08030107']"
                label="操作"
                width="190"
                fixed="right"
              >
                <template #default="productScope">
                  <el-row>
                    <el-col :span="6">
                      <el-button
                        v-has="['08030106']"
                        link
                        type="primary"
                        @click="showEditProduct(scope.row, productScope.row)"
                      >
                        编辑
                      </el-button>
                    </el-col>

                    <el-col :span="12">
                      <el-button
                        link
                        type="primary"
                        @click="showVipPriceConfigDialog(productScope.row)"
                      >
                        配置会员价
                      </el-button>
                    </el-col>

                    <el-col :span="6">
                      <el-dropdown @command="(e) => handleCommand(e, scope.row, productScope.row)">
                        <el-button
                          type="primary"
                          link
                        >
                          更多
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-item command="openRule_mall_product">
                            折扣规则
                          </el-dropdown-item>
                          <el-dropdown-item command="openRule2_mall_product">
                            限购规则
                          </el-dropdown-item>
                          <el-dropdown-item
                            v-has="['08030107']"
                            command="handleProductDelete"
                          >
                            删除
                          </el-dropdown-item>
                        </template>
                      </el-dropdown>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <goods-id />
      <goods-product-img />
      <goods-name />
      <goods-price />
      <goods-status
        :before-change="beforeChangeStatus"
        @status-changed="refreshList"
      />
      <goods-sort />
      <goods-sell-count-stock />
      <goods-stock-combined />
      <el-table-column
        v-has="[
          '08030102',
          '08030103',
          '08030104',
          '08030105'
        ]"
        label="操作"
        width="190"
        fixed="right"
      >
        <template #default="scope">
          <el-row align="middle">
            <el-col :span="6">
              <el-button
                v-has="['08030102']"
                link
                type="primary"
                @click="showEditGoods(scope.row)"
              >
                编辑
              </el-button>
            </el-col>
            <el-col :span="10">
              <el-button
                v-has="['08030104']"
                link
                type="primary"
                @click="showAddProduct(scope.row)"
              >
                新增规格
              </el-button>
            </el-col>
            <el-col :span="8">
              <el-dropdown
                placement="top"
                @command="(e) => handleCommand(e, scope.row)"
              >
                <el-button
                  type="primary"
                  link
                >
                  更多
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-has="['08030103']"
                      command="adjustStock"
                    >
                      调整库存
                    </el-dropdown-item>
                    <el-dropdown-item command="openRule_mall_goods">
                      折扣规则
                    </el-dropdown-item>
                    <el-dropdown-item command="openRule2_mall_goods">
                      限购规则
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.isHidden"
                      command="changeGoodsVisibility"
                    >
                      取消隐藏
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="!scope.row.isHidden"
                      command="changeGoodsVisibility"
                    >
                      隐藏商品
                    </el-dropdown-item>
                    <el-dropdown-item command="shareGoods">
                      分享
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-has="['08030105']"
                      command="_deleteGoods"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </layout-table>

    <!--    编辑商品-->
    <edit-goods
      v-model:show="isShowEditGoods"
      :row-data="currentEditingRow"
      submit-url="mall/admin/product/updateGoods"
      @confirm="refreshList"
    >
      <template #form-item="{ form, initialDetailText, initialDescText }">
        <edit-goods-name v-model:model-value="form.name" />
        <edit-goods-img
          v-model:model-value="form.thumbnailUrl"
          :is-add-first-text="true"
          :limit="10"
        />

        <edit-goods-category-id
          v-model:model-value="form.categoryId"
          :params="{ id: mallConfig.id }"
          url="mall/admin/category/getOnlineList"
        />
        <edit-goods-price-range v-model:model-value="form.originalPrice" />
        <GoodsAudit v-model:model-value="form.verifyFlag" />
        <edit-goods-product-limit v-model:model-value="form.productLimit" />
        <!-- <goods-exchange-limit
          v-model:product-limit="form.productLimit"
          v-model:limit-time-type="form.limitTimeType"
        /> -->
        <RechargeName
          v-if="form.type == 'recharge'"
          v-model:model-value="form.rechargeAccountRegexId"
          v-model:model-regx="form.rechargeAccountRegex"
          v-model:model-place-holder="form.rechargePlaceHolder"
        />
        <edit-goods-description
          v-model:model-value="form.description"
          :initial-value="initialDescText"
        />
        <edit-goods-detail-text
          v-model:model-value="form.detailText"
          :initial-value="initialDetailText"
        />
      </template>
    </edit-goods>

    <!--    编辑库存-->
    <edit-stock
      v-model:show="isShowEditStock"
      :is-edit-online-status="isEditOnlineStatus"
      :row-data="currentStockEditingRow"
      :column-props="['addOrDeductionStockCount']"
      products-url="mall/admin/product/getGoodsProducts"
      submit-url="mall/admin/product/saveOrUpdateProductNew"
      @confirm="editStockConfirm"
    />
    <!-- 废弃 submit-url: mall/admin/product/saveOrUpdateProductNew -->

    <!--    新增规格-->
    <add-product
      v-model:show="isShowAddProduct"
      :row-data="currentGoodsRowForAddProduct"
      :form-props="[
        'name',
        'thumbnailUrl',
        'payOfCurrencyCount',
        'payPrice',
        'addOrDeductionCount',
        'mallId',
      ]"
      submit-url="mall/admin/product/saveOrUpdateProductNew"
      store-products-url="mall/admin/product/getStoreGoodsDetail"
      @confirm="refreshList"
    >
      <template #form-item="{ form, selectedStoreProduct }">
        <product-name v-model:model-value="form.name" />
        <product-thumbnail-url v-model:model-value="form.thumbnailUrl" />
        <product-original-price-readonly
          label-str="供货价"
          :value="form.costPrice"
        />
        <product-original-price-readonly :value="form.originalPrice" />
        <product-sale-price
          v-model:model-value1="form.payOfCurrencyCount"
          v-model:model-value2="form.payPrice"
        />
        <!--        <product-total-stock :value="form.totalStock"></product-total-stock>-->
        <!--        <product-stock :value="form.stock"></product-stock>-->
        <product-before-stock :value="form.beforeStock" />
        <product-add-stock-count
          v-model:model-value="form.addOrDeductionStockCount"
          :store-row="selectedStoreProduct"
        />
      </template>
    </add-product>

    <!--    编辑规格-->
    <edit-product
      v-model:show="isShowEditProduct"
      :row-data="currentGoodsRowForEditProduct"
      :product-row-data="currentProductRowForEditProduct"
      submit-url="mall/admin/product/saveOrUpdateProductNew"
      :form-props="['name', 'thumbnailUrl', 'addOrDeductionCount']"
      @confirm="refreshList"
    >
      <template #form-item="{ form, productRowData }">
        <product-name v-model:model-value="form.name" />
        <product-thumbnail-url v-model:model-value="form.thumbnailUrl" />
        <product-original-price-readonly
          label-str="供货价"
          :value="currentProductRowForEditProduct.costPrice"
        />
        <product-original-price-readonly :value="form.originalPrice" />
        <product-sale-price
          v-model:model-value1="form.payOfCurrencyCount"
          v-model:model-value2="form.payPrice"
        />
        <product-total-stock :value="productRowData.totalStock" />
        <product-stock :value="productRowData.stock" />
        <product-before-stock :value="productRowData.beforeStock" />
        <product-add-or-deduction-stock-count
          v-model:symbol="form.addOrDeductionStockCountSymbol_fe"
          v-model:model-value="form.addOrDeductionStockCount_fe"
          :product-row-data="productRowData"
        />
      </template>
      <!-- form-item-append -->
      <template #form-item-append="{ form }">
        <product-discount-rule v-model:model-value="form.discountRule" />
        <product-purchase-rule v-model:model-value="form.payLimitRule" />
      </template>
    </edit-product>

    <select-goods v-model:show="isShowSelectGoods" />

    <DiscountRule
      :id="goodsRuleId"
      :show-dialog="dialogMessage.showDiscountRule"
      :belong="belong"
      @confirm="confirm"
      @cancel="cancel"
    />

    <PurchaseRestrictionRule
      :id="goodsRuleId"
      :show-dialog="dialogMessage.showPurchaseRule"
      :belong="belong"
      @confirm="confirm"
      @cancel="cancel"
    />

    <exportData
      v-model:show-dialog="showExportData"
      :search-data="{ ...searchForm, goodsType: 'mallGoods' }"
      title="商城商品管理"
      export-type="goodsExport"
    />

    <!-- 分享 -->
    <qr-code-dialog
      v-model:show="isShowShareDialog"
      :content="qrCodeContent"
    />

    <!-- 配置会员价格 -->
    <vip-price-config
      v-model:show="isShowVipPriceConfig"
      :product-row="currentProductRowForEditProduct"
      @finished="refreshList"
    />
  </main-content>
</template>
<script lang="ts">
export default {
  name: "MallProductList",
};
</script>
<script setup lang="ts">
import type { Ref } from "vue";
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { merchantProductTypes } from "@/config/dictionary";

import {
  // IGoodsCateItem,
  IGoodsPageData,
  IGoodsPageRow,
  IStoreProductRow,
} from "@/api/modules/pointsMall";
import {
  deleteGoods,
  getGoodsStatics,
  switchGoodsStatus,
  switchProductStatus,
  getMallInfoById,
  hideGoods,
} from "@/api/pointsMall";

import LayoutTable from "@/components/table/LayoutTable.vue";
// import EditGoods from "@/views/pointsMall/components/EditGoods.vue";
import SelectGoods from "@/views/pointsMall/components/SelectGoods.vue"
import QrCodeDialog from "./components/QrCodeDialog.vue";
import VipPriceConfig from "./components/VipPriceConfig.vue";

import { useGetGoodsCategory } from "@/views/pointsMall/compositions/useGetGoodsCategory";
import { useGetSupplier } from "@/views/pointsMall/compositions/useGetSupplier";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
// import EditSpec from "@/views/pointsMall/components/EditSpec.vue";

// refact
// 商品列表
import GoodsSupplierFilter from "@/components/goodsCenter/GoodsSupplierFilter.vue";
// import GoodsList from "@/components/goodsCenter/GoodsList.vue";
import GoodsId from "@/components/goodsCenter/goodsListColumn/GoodsId.vue";
import GoodsProductImg from "@/components/goodsCenter/goodsListColumn/GoodsProductImg.vue";
import GoodsName from "@/components/goodsCenter/goodsListColumn/GoodsName.vue";
import GoodsPrice from "@/components/goodsCenter/goodsListColumn/GoodsPrice.vue";
import GoodsStatus from "@/components/goodsCenter/goodsListColumn/GoodsStatus.vue";
import GoodsSort from "@/components/goodsCenter/goodsListColumn/GoodsSort.vue";
import GoodsSellCountStock from "@/components/goodsCenter/goodsListColumn/GoodsSellCountStock.vue";
import GoodsStockCombined from "@/components/goodsCenter/goodsListColumn/GoodsStockCombined.vue";

// 规格列表
// 规格列表
import ColProductId from "@/components/goodsCenter/productListColumn/ProductId.vue";
import ColProductName from "@/components/goodsCenter/productListColumn/ProductName.vue";
import ColProductThumbnailUrl from "@/components/goodsCenter/productListColumn/ProductThumbnailUrl.vue";
import ColProductOriginalPrice from "@/components/goodsCenter/productListColumn/ProductOriginalPrice.vue";
import ColProductSalePrice from "@/components/goodsCenter/productListColumn/ProductSalePrice.vue";
import ColProductTotalStock from "@/components/goodsCenter/productListColumn/ProductTotalStock.vue";
import ColProductStock from "@/components/goodsCenter/productListColumn/ProductStock.vue";
import ColProductSwitchOnlineStatus from "@/components/goodsCenter/productListColumn/ProductSwitchOnlineStatus.vue";
import ColProductUpdateTime from "@/components/goodsCenter/productListColumn/ProductUpdateTime.vue";

// 编辑商品
import RechargeName from "@/components/goodsCenter/addGoodsFormItem/RechargeName.vue";
import GoodsAudit from "@/components/goodsCenter/addGoodsFormItem/GoodsAudit.vue";
import EditGoods from "@/components/goodsCenter/EditGoods.vue";
import EditGoodsName from "@/components/goodsCenter/addGoodsFormItem/GoodsName.vue";
import EditGoodsCategoryId from "@/components/goodsCenter/addGoodsFormItem/GoodsCategoryId.vue";
import EditGoodsImg from "@/components/goodsCenter/addGoodsFormItem/GoodsImg.vue";
// import EditGoodsSalePrice from "@/components/goodsCenter/addGoodsFormItem/GoodsSalePrice.vue";
import EditGoodsProductLimit from "@/components/goodsCenter/addGoodsFormItem/GoodsProductLimit.vue";
import EditGoodsDescription from "@/components/goodsCenter/addGoodsFormItem/GoodsDescription.vue";
import EditGoodsDetailText from "@/components/goodsCenter/addGoodsFormItem/GoodsDetailText.vue";
import EditGoodsPriceRange from "@/components/goodsCenter/addGoodsFormItem/GoodsPriceRange.vue";
import { useEditGoods } from "@/components/goodsCenter/compositions/useEditGoods";

// 调整库存
import EditStock from "@/components/goodsCenter/EditStock.vue";
import { useEditStock } from "@/components/goodsCenter/compositions/useEditStock";

// 新增规格
import AddProduct from "@/components/goodsCenter/AddProduct.vue";
import ProductName from "@/components/goodsCenter/addProductFormItem/ProductName.vue";
import ProductThumbnailUrl from "@/components/goodsCenter/addProductFormItem/ProductThumbnailUrl.vue";
import ProductOriginalPriceReadonly from "@/components/goodsCenter/addProductFormItem/ProductOriginalPriceReadonly.vue";
import ProductSalePrice from "@/components/goodsCenter/addProductFormItem/ProductSalePrice.vue";
import ProductAddStockCount from "@/components/goodsCenter/addProductFormItem/ProductAddStockCount.vue";
import ProductBeforeStock from "@/components/goodsCenter/addProductFormItem/ProductBeforeStock.vue";
import ProductStock from "@/components/goodsCenter/addProductFormItem/ProductStock.vue";
import { useAddProduct } from "@/components/goodsCenter/compositions/useAddProduct";

// 编辑规格
import EditProduct from "@/components/goodsCenter/EditProduct.vue";
import ProductAddOrDeductionStockCount
  from "@/components/goodsCenter/addProductFormItem/ProductAddOrDeductionStockCount.vue";
import ProductTotalStock from "@/components/goodsCenter/addProductFormItem/ProductTotalStock.vue";
import ProductDiscountRule from "@/components/goodsCenter/addProductFormItem/ProductDiscountRule.vue";
import ProductPurchaseRule from "@/components/goodsCenter/addProductFormItem/ProductPurchaseRule.vue";
import { useEditProduct } from "@/components/goodsCenter/compositions/useEditProduct";

// 删除规格
import { useDeleteProduct } from "@/components/goodsCenter/compositions/useDeleteProduct";
import { ElMessage } from "element-plus/es";

// 折扣和限购规则
import DiscountRule from "@/views/pointsMall/rules/discountRule.vue";
import PurchaseRestrictionRule from "@/views/pointsMall/rules/purchaseRestrictionRule.vue";
import exportData from "@/components/exportData/exportData.vue";
// import ProductOnlineStatus from "@/components/goodsCenter/productListColumn/ProductOnlineStatus.vue";
// import ProductId from "@/components/goodsCenter/productListColumn/ProductId.vue";
// import ProductOriginalPrice from "@/components/goodsCenter/productListColumn/ProductOriginalPrice.vue";
// import ProductUpdateTime from "@/components/goodsCenter/productListColumn/ProductUpdateTime.vue";
import { useCrossPage } from "@/compositions/crossPage/useCrossPage";

// const router = useRouter();
const store = useStore();

const filterList = ref([
  {
    label: "全部",
    value: null,
    count: 0,
    fe_key: "total",
  },
  {
    label: "已上架",
    value: "1",
    count: 0,
    fe_key: "online",
  },
  {
    label: "未上架",
    value: "0",
    count: 0,
    fe_key: "offline",
  },
]);

const { goodsCateList, getGoodsCate } = useGetGoodsCategory();
const { getSupplier } = useGetSupplier();
const { mallConfig } = useMallConfig();
const isShowSelectGoods = ref(false);
const dialogMessage = ref({
  showDiscountRule: false,
  showPurchaseRule: false,
});
const goodsRuleId: Ref<number | null> = ref(null);
const belong = ref("");
const showExportData = ref(false);
const searchForm = reactive<IGoodsPageData>({
  mallId: mallConfig.value.id,
  onlineStatus: null,
  categoryId: null,
  type: null,
  name: "",
  prePrice: null,
  aftPrice: null,
  storeId: null,
  queryInsIds: [],
  currentPage: 1,
  showCount: 10,
  withProducts: true,
  goodsType: "",
});
const route = useRoute()
watch(() => route.params, (val) => {
  if (val){
    searchForm.name = val.goodsName || ''
  }
}, { immediate: true })

const goodsIds = computed(() => {
  return store.state.pointsMall.goodsIds.filter(Boolean)
})
//清除跳转的参数
watch(searchForm, () => {
  store.commit("pointsMall/updateGoodsIds", [])
}) 

watch(goodsIds, (val) => {
  if (val.length){
    let timer = setTimeout(() => {
      clearTimeout(timer)
      refreshList() 
    }, 100);
  }
})
const openRule = (row: IGoodsPageRow | IStoreProductRow, type: string) => {
  goodsRuleId.value = row.id;
  belong.value = type;
  dialogMessage.value.showDiscountRule = true;
};
const openRule2 = (row: IGoodsPageRow | IStoreProductRow, type: string) => {
  goodsRuleId.value = row.id;
  belong.value = type;
  dialogMessage.value.showPurchaseRule = true;
};
const confirm = () => {
};
const cancel = (type: string | number) => {
  dialogMessage.value[type] = false;
};
// const operatingRow = ref<IGoodsPageRow>();

const showGoodSelect = () => {
  isShowSelectGoods.value = true;
};

const _deleteGoods = (row: IGoodsPageRow) => {
  ElMessageBox.confirm("确定删除？", "提示").then(async () => {
    const rs = await deleteGoods({ id: row.id, name: row.name });
    if (rs.code === 200) {
      ElMessage.success("删除成功");
      goodsListRef.value?.research();
    }
  });
};

const _getGoodsStatics = async () => {
  const rs = await getGoodsStatics({ id: mallConfig.value.id });

  if (rs.code === 200) {
    let target = filterList.value.find((item) => item.fe_key === "online");
    target!.count = rs.payload?.onlineAmount ?? 0;
    target = filterList.value.find((item) => item.fe_key === "offline");
    target!.count = rs.payload?.offlineAmount ?? 0;
    target = filterList.value.find((item) => item.fe_key === "total");
    target!.count = rs.payload?.totalAmount ?? 0;
  }
};


const handleRowClick = (row: IGoodsPageRow, expanded?: boolean) => {
  goodsListRef.value?.$refs.elTable?.toggleRowExpansion(row, expanded);
}

const handleCommand = (command: string, goodsRow: IGoodsPageRow, productRow?: IStoreProductRow) => {
  switch (command) {
    case "adjustStock":
      adjustStock(goodsRow)
      break;
    case "_deleteGoods":
      _deleteGoods(goodsRow)
      break;
    case "openRule_mall_goods":
      openRule(goodsRow, "mall_goods")
      break;
    case "openRule2_mall_goods":
      openRule2(goodsRow, "mall_goods")
      break;
    case "handleProductDelete":
      handleProductDelete(
        'mall/admin/product/delProduct',
        productRow!,
        goodsRow,
      );
      break;
    case "openRule_mall_product":
      openRule(productRow!, 'mall_product');
      break;
    case "openRule2_mall_product":
      openRule2(productRow!, 'mall_product');
      break;
    case "changeGoodsVisibility":
      changeGoodsVisibility(goodsRow);
      break;
    case "shareGoods":
      shareGoods(goodsRow);
      break;
    default:
      console.log("command not found", command);
  }
}

// 显示商品库存调整弹窗
const adjustStock = (goodsRow: IGoodsPageRow) => {
  isEditOnlineStatus.value = false;
  showEditStock(goodsRow, { openWay: 'normal' })
}

// 改变商品是否在商城曝光展示
const changeGoodsVisibility = async (goodsRow: IGoodsPageRow) => {
  const rs = await hideGoods({ id: goodsRow.id })
  if (rs.code === 200) {
    refreshList()
  }
}

// 分享商品
const isShowShareDialog = ref(false);
const qrCodeContent = ref("");
const shareGoods = async (goodsRow: IGoodsPageRow) => {
  isShowShareDialog.value = true;
  currentEditingRow.value = goodsRow;
  const rs = await getMallInfoById(mallConfig.value.id);
  if (rs.code === 200) {
    let url = ""
    url += `${window.VUE_APP_URL[import.meta.env.MODE].userPath}${store.state.user.merchant.merchantCode}#`
    url += `/mall/${rs.payload.mallCode}/app/detail?`
    url += `goodsId=${goodsRow.id}&`
    url += `originalType=mall`
    qrCodeContent.value = url;
  }
}

// 配置会员价格
const isShowVipPriceConfig = ref(false)
const showVipPriceConfigDialog = (row: IStoreProductRow) => {
  isShowVipPriceConfig.value = true
  currentProductRowForEditProduct.value = row
}

// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});

watch(
  () => insId,
  () => {
    if (mallConfig.value.id) {
      getSupplier({
        defaultStore: -1
      });
      getGoodsCate();
      _getGoodsStatics();
    }
  },
  {
    deep: true,
  }
);

// 表格渲染
const goodsListRef = ref<InstanceType<typeof LayoutTable> | null>(null);

const refreshList = () => {
  console.log("refreshList")
  goodsListRef.value?.research();
};

//上架商品编辑库存规格状态
const isEditOnlineStatus = ref(false);
const currentStatusChangingRow = ref<IGoodsPageRow>();
const beforeChangeStatus = (row: IGoodsPageRow) => {
  currentStatusChangingRow.value = row;
  return new Promise(async (resolve) => {
    if (row.onlineStatus) {
      ElMessageBox.confirm(
        "商品下架，商品规格库存将全部归还，是否确认下架？",
        "提示"
      )
        .then(async () => {
          const rs = await switchGoodsStatus({
            id: row.id,
            name: row.name,
            onlineStatus: 0,
          });
          if (rs.code === 200) {
            resolve(true);
          }
        })
        .catch(() => {
          // cancel
          resolve(false);
        });
    } else {
      isEditOnlineStatus.value = true;
      showEditStock(row, { openWay: "onlineStatus" });
    }
  });
};

const _switchProductStatus = (row: IStoreProductRow) => {
  return new Promise(async (resolve) => {
    if (row.onlineStatus === 1) {
      ElMessageBox.confirm("确认下架此规格？", "提示")
        .then(async () => {
          const rs = await switchProductStatus({ id: row.id, name: row.name });
          if (rs.code === 200) {
            resolve(true);
          } else {
            resolve(false);
          }
        })
        .catch(() => {
          resolve(false);
        });
    } else {
      const rs = await switchProductStatus({ id: row.id, name: row.name });
      if (rs.code === 200) {
        resolve(true)
      } else {
        resolve(false);
      }
    }
  });
};

// 编辑商品
const { isShowEditGoods, showEditGoods, currentEditingRow } = useEditGoods();

// 编辑库存
const { isShowEditStock, showEditStock, currentStockEditingRow } = useEditStock();
const editStockConfirm = async ({ rowData, data }: { rowData: IGoodsPageRow, data }) => {
  if (isEditOnlineStatus.value && data?.length) {
    const spes = data.map((item) => ({
      id: item.id,
      onlineStatus: item.onlineStatus,
      // type: item.addOrDeductionStockCount > 0 ? 1 : 2,
      // stock: Math.abs(item.addOrDeductionStockCount),
      type: item.addOrDeductionStockCountSymbol_fe === "+" ? '1' : '2',
      stock: Math.abs(item.addOrDeductionStockCount_fe),
    }));
    const rs = await switchGoodsStatus({
      id: rowData.id,
      name: rowData.name,
      onlineStatus: 1,
      spes: spes,
    });
    if (rs.code === 200) {
      refreshList();
    }
  } else {
    refreshList();
  }

  isEditOnlineStatus.value = false;
};

// 新增规格
const { isShowAddProduct, showAddProduct, currentGoodsRowForAddProduct } =
  useAddProduct();

// 编辑规格
const {
  isShowEditProduct,
  showEditProduct,
  currentGoodsRowForEditProduct,
  currentProductRowForEditProduct,
} = useEditProduct();

// 删除规格
const { handleProductDelete } = useDeleteProduct();

// 跨页刷新回调
useCrossPage("pointsMall", { refreshList });


onMounted(() => {
  if (mallConfig.value.id) {
    getSupplier({
      defaultStore: -1
    });
    getGoodsCate();
    _getGoodsStatics();
  }
});
</script>

<style scoped lang="scss">
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.row-img-wrapper {
  width: 100px;
  height: 100px;
}
</style>
